package cn.com.util;

public class CRC16 {
	private static final int POLYNOMIAL = 0xA001; // CRC-16/Modbus多项式

	public static int calculateCRC16(byte[] data) {
		int crc = 0x0000; // 初始值

		for (byte b : data) {
			crc ^= (b & 0xFF); // 与当前字节异或
			for (int i = 0; i < 8; i++) {
				if ((crc & 0x0001) != 0) {
					crc = (crc >>> 1) ^ POLYNOMIAL;
				} else {
					crc = crc >>> 1;
				}
			}
		}

		return crc;
	}

	public static byte[] getCRC16Bytes(byte[] data) {
		int crc = calculateCRC16(data);
		// 高字节在前
		return new byte[] { (byte) ((crc >> 8) & 0xFF), (byte) (crc & 0xFF) };
	}
	
	public static void main(String[] args) {
		// 测试示例
		String datacheck = "00002A0018802025041400000300000000000000000000";
		byte[] _datacheckcrc16Bytes = CRC16.getCRC16Bytes(HexUtil.hexStringToByteArray(datacheck));
		String _datacheck = HexUtil.byteArrayToHexString(_datacheckcrc16Bytes);
		
		System.out.println("FA"+datacheck+_datacheck);
	}
	// 34D3
}
